import React, { useContext, useEffect, useCallback, useState } from 'react';
import { useHistory } from 'react-router-dom'
import { myContext } from '../../../../reducer'
import { awaitPlanTypeEnum } from '../../enum'
import { postSofPdPlanActFindTodo, getSofPdPlanActGiveUp, getSofPdPlanActDelivery } from '../../api'
import SelectModules from './Components/SelectModules'
import DistributionModule from './Components/DistributionModule'
import NextModule from './Components/NextModule'
import { AwaitPlanAll } from "./style";
import { PageHeader, message, Table, Space, Button, Modal } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons';

const { confirm } = Modal;

/**
 * @description: 待办任务--我的任务/部门任务列表
 * @author: xiaoxujs
 * @updata: xiaoxujs（2021-08-27）待办任务列表, 新增两个字段 : 任务名称(taskName)需要展示到列表, actId:不需要展示,完成任务时携带该参数
 */

const AwaitPlan = () => {
    const history = useHistory()
    const { state } = useContext(myContext)
    const [listData, setListData] = useState([])
    const [total, setTotal] = useState(0)
    const [currentPage, setCurrentPage] = useState(1)
    const [size, setSize] = useState(10)
    const [selectData, setSelectData] = useState({})
    const [clickId, setClickId] = useState(undefined)
    const [clickTaskId, setClickTaskId] = useState(undefined)
    const [distributionModuleShow, setDistributionModuleShow] = useState(false)
    const [distribution, setDistribution] = useState(true)
    const [nextModuleShow, setNextModuleShow] = useState(false)
    const [clickActId, setClickActId] = useState(undefined)
    const [clickTaskName, setClickTaskName] = useState(undefined)
    const listFun = useCallback(
        (parames = {
            currentPage: 1,
            size: 10
        }) => {
            parames.menu = state.awaitPlanType
                ; (async () => {
                    const { code, msg, data } = await postSofPdPlanActFindTodo(parames)
                    if (code === '20000') {
                        setListData(data.records)
                        setTotal(data.total)
                        setCurrentPage(parames.currentPage)
                        setSize(parames.size)
                    } else {
                        message.error(msg)
                    }
                })()
        },
        [state.awaitPlanType],
    )
    useEffect(() => {
        listFun()
    }, [listFun])
    //分页
    const pagination = {
        //是否可以改变pagesize//
        showSizeChanger: true,
        //是否可以快速跳转到某页
        showQuickJumper: true,
        //展示一共有多少条数据//
        showTotal: () => `共${total}条`,
        //每页条数
        pageSize: size,
        //当前页数
        current: currentPage,
        //数据总数
        total: total,
        //pageSize 变化的回调
        onShowSizeChange: (current, pageSize) => changePageSize(pageSize, current),
        //页码改变的回调，参数是改变后的页码及每页条数
        onChange: (current) => changePage(current),
    }
    //改变每页条数
    const changePageSize = (pageSizeFun, current) => {
        const parames = {
            currentPage: current,
            size: pageSizeFun,
            ...selectData
        }
        listFun(parames);
    }
    //改变页数
    const changePage = (current) => {
        const parames = {
            currentPage: current,
            size,
            ...selectData
        }
        listFun(parames);
    }
    //分配计划
    const handleDistributionPlan = (id, taskId) => {
        setClickId(id)
        setClickTaskId(taskId)
        setDistribution(true)
        setDistributionModuleShow(true)
    }
    //分配计划
    const handlePickUp = (id, taskId) => {
        setClickId(id)
        setClickTaskId(taskId)
        setDistribution(false)
        setDistributionModuleShow(true)
    }
    //保持数据列表
    const handleDistributionModuleFun = () => {
        const parames = {
            currentPage,
            size,
            ...selectData
        }
        listFun(parames);
    }
    //归还
    const handleDelete = (id, taskId) => {
        confirm({
            title: '确定要归还任务吗?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                ; (async () => {
                    const { code, msg } = await getSofPdPlanActGiveUp({ actId: taskId, pdplanId: id })
                    if (code === '20000') {
                        message.success('归还成功！')
                        handleDistributionModuleFun()
                    } else {
                        message.error(msg)
                    }
                })()
            }
        });
    }
    //归还
    const handleDeliverGoods = (id, taskId) => {
        confirm({
            title: '确定要发货吗?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                ; (async () => {
                    const { code, msg } = await getSofPdPlanActDelivery({ taskId: taskId, pdPlanId: id })
                    if (code === '20000') {
                        message.success('发货成功')
                        handleDistributionModuleFun()
                    } else {
                        message.error(msg)
                    }
                })()
            }
        });
    }
    //下发
    const handleNext = (id, taskId, actId, taskName) => {
        setClickId(id)
        setClickTaskId(taskId)
        setClickActId(actId)
        setClickTaskName(taskName)
        setNextModuleShow(true)
    }
    //进入详情
    const handleEnterDetails = (id) => {
        history.push({pathname: '/productionPlan/details', state: {
            pdPlanId: id
        }})
    }
    const columns = [
        {
            title: '客户名称',
            dataIndex: 'clientName',
            render: (text, recode) => <Button type = 'link' onClick = {() => handleEnterDetails(recode.id)}>{text}</Button>
        },
        {
            title: '任务名称',
            dataIndex: 'taskName'
        },
        {
            title: '合同编号',
            dataIndex: 'conNo'
        },
        {
            title: '产品',
            dataIndex: 'product'
        },
        {
            title: '计划下发时间',
            dataIndex: 'ptlStartDate'
        },
        {
            title: '计划下发时间',
            dataIndex: 'ptlStartDate'
        },
        {
            title: '下发人员',
            dataIndex: 'releaseUser'
        },
        {
            title: '剩余天数',
            dataIndex: 'daysRemaining'
        },
        {
            title: '执行人',
            dataIndex: 'assignName'
        },
        {
            title: '分配时间',
            dataIndex: 'assignDate'
        },
        {
            title: '业务员',
            dataIndex: 'sellName'
        },
        {
            title: '状态',
            dataIndex: 'state'
        },
        {
            title: '操作',
            render: (text, recode) => <Space>
                {
                    state.awaitPlanType === 1 ? <>
                        <Button type='primary' onClick={() => handleDistributionPlan(recode.id, recode.taskId)}>分配</Button>

                        {
                            recode.assignName ? null : <Button type='primary' onClick={() => handlePickUp(recode.id, recode.taskId)} >拾取</Button>
                        }

                    </> : null
                }
                {
                    state.awaitPlanType === 0 ? <>
                        <Button type='primary' onClick={() => handleDelete(recode.id, recode.taskId)}>归还</Button>
                        <Button type='primary' onClick={() => handleNext(recode.id, recode.taskId, recode.actId, recode.taskName)}>下发</Button>
                        <Button type='primary' onClick={() => handleDeliverGoods(recode.id, recode.taskId)}>发货</Button>
                        {/* <Button type='primary' onClick={() => handleDistributionPlan(recode.id, recode.taskId)}>申请外协</Button> */}
                    </> : null
                }

            </Space>
        }
    ];
    return <AwaitPlanAll>
        <PageHeader
            className="site-page-header"
            title={awaitPlanTypeEnum[state.awaitPlanType]}
        />
        <SelectModules setSelectData={setSelectData} listFun={listFun} />
        <Table dataSource={listData} columns={columns} pagination={pagination} rowKey='id' />
        <DistributionModule
            distributionModuleShow={distributionModuleShow}
            setDistributionModuleShow={setDistributionModuleShow}
            clickId={clickId}
            clickTaskId={clickTaskId}
            handleDistributionModuleFun={handleDistributionModuleFun}
            distribution={distribution}
        />
        <NextModule
            nextModuleShow={nextModuleShow}
            setNextModuleShow={setNextModuleShow}
            clickId={clickId}
            clickTaskId={clickTaskId}
            clickActId = {clickActId}
            clickTaskName = {clickTaskName}
            handleDistributionModuleFun={handleDistributionModuleFun}
        />
    </AwaitPlanAll>
}

export default AwaitPlan;